package com.zlz.m3u8download.bean;

import com.alibaba.fastjson2.annotation.JSONField;
import com.zlz.m3u8download.bean.entity.CacheM3u8Entity;
import com.zlz.m3u8download.bean.entity.M3u8HLCFileEntity;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.util.*;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.atomic.AtomicInteger;

@Data
@Builder
public class RunTimeTask {

    private Long taskId;

    @JSONField(serialize = false)
    private Map<Integer, M3u8HLCFileEntity> fragments;

    private final Integer startCode;

    private Integer minCode;

    private Integer maxCode;

    @JSONField(serialize = false)
    private final Set<Integer> waitingTaskCode = new ConcurrentSkipListSet<>();

    @JSONField(serialize = false)
    private final Set<Integer> runningTaskCode = new HashSet<>();

    private volatile boolean running;

    public synchronized void updateRunningTask(Integer code, boolean add) {
        synchronized (this) {
            if (add) {
                runningTaskCode.add(code);
                return;
            }
            runningTaskCode.remove(code);
        }
    }

    public synchronized void updateFailedTask(Integer code, boolean add) {
        synchronized (this) {
            if (add) {
                waitingTaskCode.add(code);
                return;
            }
            waitingTaskCode.remove(code);
        }
    }

    public void setFragments(Map<Integer, M3u8HLCFileEntity> fragments) {
        this.fragments = fragments;
        this.waitingTaskCode.addAll(fragments.keySet());
    }
}
